﻿// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!");

using Consul;
using Grpc.Core;
using Grpc.Net.Client;
using IGrpcServer;
using MagicOnion.Client;
using Microsoft.AspNetCore.Builder;
using System.Threading.Channels;
using Consul.Framework.ConsulExtends;
using static Consul.Framework.ConsulExtends.ConsulExtend;
using Consul.Framework.ConsulExtends.ClienExtend;
using Microsoft.Extensions.DependencyInjection;
using Consul.Framework;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

#region Https
//// Connect to the server using gRPC channel.
//var channel = GrpcChannel.ForAddress("https://localhost:7062");

//// NOTE: If your project targets non-.NET Standard 2.1, use `Grpc.Core.Channel` class instead.
//// var channel = new Channel("localhost", 5001, new SslCredentials());

//// Create a proxy to call the server transparently.
//var client = MagicOnionClient.Create<IComputeData>(channel);

//// Call the server-side method using the proxy.
//var result = await client.SumAsync(123, 456);
//Console.WriteLine($"Result: {result}");
#endregion

#region Https使用IP
////显式的指定HTTP/2不需要TLS支持
//AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
//AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);

// 然后你就可以根据IP和端口拿到对于的服务
var channel = GrpcChannel.ForAddress("https://10.100.25.73:7062", new GrpcChannelOptions()
{
    HttpClient = null,
    HttpHandler = new HttpClientHandler
    {
        //方法一
        ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        //方法二
        //ServerCertificateCustomValidationCallback = (a, b, c, d) => true
    }
});

// NOTE: If your project targets non-.NET Standard 2.1, use `Grpc.Core.Channel` class instead.
// var channel = new Channel("localhost", 5001, new SslCredentials());

// Create a proxy to call the server transparently.
var client = MagicOnionClient.Create<IComputeData>(channel);

//// Call the server-side method using the proxy.
//var result = await client.SumAsync(123, 456);
//Console.WriteLine($"Result: {result}");
#endregion

#region Consul Client
//var services = await AvaliableServices("base-appmarket", "");
async Task<ServiceEntry[]> AvaliableServices(string name, string tags)
{
    var services = new List<ServiceEntry>();
    using (var client = new ConsulClient(new ConsulClientConfiguration() {Address=new Uri("http://10.221.252.21:8500") }))
    {
        foreach (var tag in tags.Split(','))
        {
            var result = await client.Health.Service(name, !string.IsNullOrEmpty(tag) ? tag : null, true).ConfigureAwait(false);
            foreach (var item in result.Response)
            {
                if (!services.Any(service => service.Node.Address == item.Node.Address
                    && service.Service.Port == item.Service.Port))
                {
                    services.Add(item);
                }
            }
        }
        //交集处理，仅取出完全匹配服务
        foreach (var tag in tags.Split(','))
        {
            if (string.IsNullOrEmpty(tag))
            {
                continue;
            }
            var alsorans = services.Where(service => !service.Service.Tags.Contains(tag)).ToList();
            foreach (var alsoran in alsorans)
            {
                services.Remove(alsoran);
            }
        }
    }
    return services.ToArray();
}
#endregion

//var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddConsulDispatcher(ConsulDispatcherType.Polling);

//var app = builder.Build();
//var option = app.Services.GetService<IOptionsMonitor<ConsulRegisterOptions>>();
//AbstractConsulDispatcher dispatcher = builder.Services.BuildServiceProvider().GetService<AbstractConsulDispatcher>() ?? new AverageDispatcher(option);
////AbstractConsulDispatcher dispatcher1 = app.Services.GetService<AbstractConsulDispatcher>();
//var realUrl = dispatcher?.ChooseAddress("base-appmarket");
//var dd = 1;

#region consul Test
IConfigurationRoot root = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();

var servicesT = new ServiceCollection(); 
servicesT.AddOptions();
servicesT.Configure<ConsulOptions>(root.GetSection("ConsulOptions"));
var provider = servicesT.BuildServiceProvider();
//TestOptions optionT = provider.GetRequiredService<TestOptions>();
var option1 = provider.GetRequiredService<IOptions<ConsulOptions>>();
var server = option1.Value?.Server;

public class ConsulOptions
{
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; } = "Consul";
    /// <summary>
    /// server地址
    /// </summary>
    public string Server { get; set; } = "http://localhost:8500";
}
#endregion
